<?php

namespace App\Http\Controllers\EmberApi;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class PaymentsController extends Controller
{
    //
    public function index(){
        $cache = Redis::get('xdagpoolpayments');
        $stats = json_encode([]);
        if(!isset($cache)){
            $stats = $this->getData();
            Redis::setex('xdagpoolpayments',60,$stats);
            $stats = json_decode($stats);
        }else{
            $stats = json_decode($cache);
        }
        return response()->json($stats);
    }

    protected function getData(){
        $jsonArray = [];
        $payments = DB::table('payouts')
            ->latest()
            ->limit(50)
            ->get();
        //var_dump($payments);
        $paymentCount = DB::table('payouts')->count();
        $jsonArray['paymentsTotal'] = $paymentCount;
        $i = 0;
        $foundBlocks = [];
        foreach ($payments as $payment) {
            //$jsonArray['payments'][$i]['address'] = $payment->recipient;
            $recipientAddress = $payment->recipient;
            $jsonArray['payments'][$i]['address'] = substr($recipientAddress,0,5).'...'.substr($recipientAddress,-5);
            $jsonArray['payments'][$i]['timestamp'] =strtotime($payment->made_at);
            $jsonArray['payments'][$i]['amount'] = $payment->amount;
            $blockid = $payment->found_block_id;
            if (empty($foundBlocks[$blockid])){
                $foundbBlock = DB::table('found_blocks')->where('id',$blockid)->first();
                $foundBlocks[$blockid] = $foundbBlock->address;
                //var_dump($foundBlocks[$blockid]);
            }
            $jsonArray['payments'][$i]['foundBlock'] = $foundBlocks[$blockid];
            $i++;
        }
        //return response()->json($jsonArray);
        return json_encode($jsonArray);

    }
}
